package com.fulihui.wgj.service.mass;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.fulihui.common.builder.rpc.RpcResultBuilder;
import com.fulihui.common.conv.BeanConv;
import com.fulihui.common.enums.SendLogStatusEnum;
import com.fulihui.common.error.Errors;
import com.fulihui.common.error.InvokeServiceException;
import com.fulihui.common.result.rpc.BaseResult;
import com.fulihui.common.result.rpc.SimpleResult;
import com.fulihui.common.util.ConditionValidator;
import com.fulihui.weixinsdk.model.MaterialContent;
import com.fulihui.weixinsdk.model.MaterialItem;
import com.fulihui.wgj.dal.mybatis.domain.WxMassMsgLog;
import com.fulihui.wgj.dal.mybatis.repository.WxMassMsgLogRepository;
import com.fulihui.wgj.facade.dto.WxMassMsgLogDTO;
import com.fulihui.wgj.facade.request.mass.MassLogSendUpdateRequest;
import com.fulihui.wgj.facade.request.mass.WxMassLogCancelRequest;
import com.fulihui.wgj.facade.request.mass.WxMassLogPageQueryRequest;
import com.fulihui.wgj.facade.result.mass.WxMassLogPageResult;
import com.fulihui.wgj.facade.service.mass.WxMassLogService;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 图文发送记录Service
 *
 * @author wang_wx
 * @date 2018-08-01
 */
@Component
@Service(interfaceClass = WxMassLogService.class, version = "1.0.0", timeout = 5000)
public class WxMassLogServiceImpl implements WxMassLogService {

    private static final Logger LOGGER = LoggerFactory.getLogger(WxMassLogServiceImpl.class);

    @Autowired
    WxMassMsgLogRepository wxMassMsgLogRepository;

    @Override
    public WxMassLogPageResult pageQuerySendLogs(WxMassLogPageQueryRequest request) throws InvokeServiceException {
        ConditionValidator.validate(request);
        PageInfo<WxMassMsgLog> pageInfo = wxMassMsgLogRepository.queryPageListByExample(buildPageQueryExample(request), request.getPage(), request.getRows());
        long total = pageInfo.getTotal();
        WxMassLogPageResult result = RpcResultBuilder.succPageResult(WxMassLogPageResult.class, pageInfo.getPageNum(), pageInfo.getPageSize(), Math.toIntExact(total));
        if (total > 0) {
            List<WxMassMsgLogDTO> logDTOS = BeanConv.copy(pageInfo.getList(), WxMassMsgLogDTO.class);
            if (!CollectionUtils.isEmpty(logDTOS)) {
                logDTOS.forEach(wxMassMsgLogDTO -> {
                    String msgContent = wxMassMsgLogDTO.getMsgContent();
                    // 推文json数据-获取推文篇数
                    if (StringUtils.isNotBlank(msgContent)) {
                        try {
                            MaterialContent newsMessage = JSON.parseObject(msgContent, MaterialContent.class);
                            List<MaterialItem> newsItem = newsMessage.getNews_item();
                            if (!CollectionUtils.isEmpty(newsItem)) {
                                wxMassMsgLogDTO.setHeadTitle(newsItem.get(0).getTitle());
                                wxMassMsgLogDTO.setHeadPicUrl(newsItem.get(0).getThumb_url());
                                wxMassMsgLogDTO.setArticleCount(newsItem.size());
                            }
                        } catch (Exception e) {
                            LOGGER.error("图文群发记录-获取推文篇数异常" + e);
                        }
                    }
                });
            }
            result.setValue(logDTOS);
        }
        return result;
    }

    /**
     * 组装条件
     *
     * @param request
     * @return
     */
    Example buildPageQueryExample(WxMassLogPageQueryRequest request) {
        Example example = new Example(WxMassMsgLog.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(request.getTitle())) {
            criteria.andLike("title", "%" + request.getTitle() + "%");
        }
        if (StringUtils.isNotBlank(request.getBeginDate())) {
            criteria.andGreaterThanOrEqualTo("gmtModified", request.getBeginDate());
        }
        if (StringUtils.isNotBlank(request.getEndDate())) {
            criteria.andLessThanOrEqualTo("gmtModified", request.getEndDate());
        }
        if (StringUtils.isNotBlank(request.getSendStatus())) {
            criteria.andEqualTo("sendStatus", request.getSendStatus());
        }
        example.orderBy("gmtModified").desc();
        return example;
    }

    @Override
    public BaseResult updateMassLogAccumulate(MassLogSendUpdateRequest request) throws InvokeServiceException {
        ConditionValidator.validate(request);
        WxMassMsgLog exist = wxMassMsgLogRepository.queryById(request.getId());
        if (Objects.isNull(exist)) {
            return RpcResultBuilder.fail(Errors.Commons.RECORD_NOT_EXISTS);
        }
        WxMassMsgLog wxMassMsgLogUpdate = new WxMassMsgLog();
        wxMassMsgLogUpdate.setId(request.getId());
        wxMassMsgLogUpdate.setGmtModified(new Date());
        wxMassMsgLogUpdate.setSendStatus(request.getSendStatus());
        wxMassMsgLogUpdate.setSuccessTotal(request.getSuccessTotal());
        wxMassMsgLogUpdate.setFailTotal(request.getFailTotal());
        wxMassMsgLogUpdate.setSendStartTime(request.getSendStartTime());
        wxMassMsgLogUpdate.setSendEndTime(request.getSendEndTime());
        Integer count = wxMassMsgLogRepository.updateAccumulate(wxMassMsgLogUpdate);
        return count > 0 ? RpcResultBuilder.succ() : RpcResultBuilder.fail(Errors.Commons.UPDATE_FAILED);
    }

    @Override
    public SimpleResult<List<WxMassMsgLogDTO>> queryMassLogs4Job() {
        List<WxMassMsgLog> wxMassMsgLogs = wxMassMsgLogRepository.queryByExample(buildExample4Job());
        List<WxMassMsgLogDTO> massMsgLogDTOS = null;
        if (!CollectionUtils.isEmpty(wxMassMsgLogs)) {
            massMsgLogDTOS = BeanConv.copy(wxMassMsgLogs, WxMassMsgLogDTO.class);
        }
        LOGGER.info("massMsgLogDTOS 4Job = {}", massMsgLogDTOS);
        return RpcResultBuilder.succSimple(massMsgLogDTOS);
    }

    private Example buildExample4Job() {
        Example example = new Example(WxMassMsgLog.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("jobStatus", Boolean.TRUE);
        criteria.andEqualTo("sendStatus", SendLogStatusEnum.await.getCode());
        example.orderBy("jobTime").asc();
        return example;
    }

    @Override
    public BaseResult cancelMassLog(WxMassLogCancelRequest request) throws InvokeServiceException {
        ConditionValidator.validate(request);
        WxMassMsgLog exist = wxMassMsgLogRepository.queryById(request.getId());
        if (Objects.isNull(exist)) {
            return RpcResultBuilder.fail(Errors.Commons.RECORD_NOT_EXISTS);
        }
        if (!exist.getJobStatus() || !SendLogStatusEnum.await.getCode().equals(exist.getSendStatus())) {
            return RpcResultBuilder.fail(Errors.MassError.NO_JOB_LOG_CANNOT_CANCEL);
        }
        WxMassMsgLog wxMassMsgLogUpdate = new WxMassMsgLog();
        wxMassMsgLogUpdate.setId(request.getId());
        wxMassMsgLogUpdate.setSendStatus(SendLogStatusEnum.cancel.getCode());
        Integer count = wxMassMsgLogRepository.updateSelective(wxMassMsgLogUpdate);
        return count > 0 ? RpcResultBuilder.succ() : RpcResultBuilder.fail(Errors.Commons.UPDATE_FAILED);
    }
}
